import json
from django.http import JsonResponse
from django.shortcuts import render
from .models import Usermodel
# Create your views here.
from django.views import View

class UserView(View):
    def get(self,req):
        pagesize=int(req.GET.get("size"))
        pagenum=int(req.GET.get("page"))
        start=(pagenum-1)*pagesize
        end=start+pagesize
        if req.GET.get('username'):
            data = Usermodel.objects.filter(username__contains=req.GET.get('username'))[start:end].values()
            total = len(Usermodel.objects.filter(username__contains=req.GET.get('username')))
        else:
            data=Usermodel.objects.values()[start:end]
            total=len(Usermodel.objects.values())
        return JsonResponse({"code":200,"data":list(data),"total":total})
    def post(self,req):
        d=json.loads(req.body)
        u=Usermodel.objects.create(**d)
        return JsonResponse({"message":"获取成功","code":200})
    def put(self,req,id):
        d=json.loads(req.body)
        Usermodel.objects.filter(id=id).update(username=d['username'],password=d['password'],role=d['role'])
        return JsonResponse({"message":"修改成功","code":200})
    def delete(self,req,id):
        Usermodel.objects.filter(id=id).delete()
        return JsonResponse({"message":"删除成功","code":200})


def login(req):
    d=json.loads(req.body)
    user=Usermodel.objects.filter(username=d['username'],password=d['password']).values()
    print(user)
    if user[0]['role'] == '管理员':
        return JsonResponse({'code': 20000, 'data': {'token': "admin"}})
    else:
        return JsonResponse({'code': 20000, 'data': {'token': "editor"}})
def info(req):
    if req.GET.get('token') == 'admin':
        return JsonResponse({'code': 20000, 'data': {'roles': ['admin'],
        'introduction': 'I am a super administrator',
        'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        'name': 'Super Admin'}})
    elif req.GET.get('token') == 'editor':
        return JsonResponse({'code': 20000, 'data': {'roles': ['editor'],
        'introduction': 'I am a super administrator',
        'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        'name': 'Super Admin'}})
def logout(req):

    return JsonResponse({'code': 20000, 'data': 'success'})
